/**
 * 教研老师添加科研题目
 * 
 * /jiaoyan/topic/add
 */


const Year = require('../../../models/years')
const Topics= require('../../../models/researchTopics')
const User_Info = require('../../../models/usersInfo')
const utils = require('../../../utils/index')
const $ = require('../../../utils/common')

const add = async function (req, res) {        
    try {
        // set a relation with years
        if (!req.body.year_id) {
            $.sendMessage(res, 1015, '参数year_id不能缺少')
            return
        }

        var year_info = await Year.findOne({
            where: {
                id: req.body.year_id,
                type: '0'
            },
            attributes: ['id', 'createdAt', 'dead_line']
        })

        if (year_info == null) {
            $.sendMessage(res, 1015, '无效年度id')
            return
        }
        
        // get teacher fullname
        var teacher_user_name = req.user_name

        var teacher_info = await User_Info.findOne({
            where: {
                user_name: teacher_user_name
            },
            attributes: ['id', 'user_fullname', 'user_name', 'user_email', 'user_phone', 'user_address']
        })

        if (teacher_info == null) {
            $.sendMessage(res, 1015, '无效user_name')
            return
        }

        // 需要把教师的姓名和校园卡和插入到表
        req.body['teacher_fullname'] = teacher_info.dataValues.user_fullname
        req.body['teacher_user_name'] = teacher_info.dataValues.user_name
        delete req.body.id
        req.body['years'] = year_info.dataValues.id
        req.body['srart_time'] = year_info.dataValues.createdAt + ''
        req.body['end_time'] = year_info.dataValues.dead_line + ''
        req.body['teacher_email'] = teacher_info.dataValues.user_email
        req.body['teacher_address'] = teacher_info.dataValues.user_address
        req.body['teacher_phone'] = teacher_info.dataValues.user_phone

        // 新增课题
        await Topics.create(req.body)

        res.json({
            code: 200,
            message: '添加成功',
        })
            
        // 日志
        utils.create_a_log(req, '科研题目管理', '添加')
        return
    }
    catch(error) {
        res.json({
            message: "抓到异常",
            error: 'error' + error
        })
        utils.create_a_log(req, '科研题目管理', '添加', '失败')
        return
    } 
}
    
module.exports = add